package com.example.javaai.service;

import com.example.javaai.dto.StreamResponse;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.StreamingChatClient;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

@Service
public class AiService {
    private final ChatClient chatClient;
    private final StreamingChatClient streamingChatClient;

    public AiService(ChatClient chatClient, StreamingChatClient streamingChatClient) {
        this.chatClient = chatClient;
        this.streamingChatClient = streamingChatClient;
    }

    public String chat(String message) {
        Prompt prompt = new Prompt(new UserMessage(message));
        ChatResponse response = chatClient.call(prompt);
        return response.getResult().getOutput().getContent();
    }

    public Flux<StreamResponse> chatStream(String message) {
        Prompt prompt = new Prompt(new UserMessage(message));
        return streamingChatClient.stream(prompt)
                .map(response -> {
                    String content = response.getResult().getOutput().getContent();
                    return new StreamResponse(content, false);
                })
                .concatWith(Flux.just(new StreamResponse("", true)));
    }
}